#include "UdpClient.h"


namespace mp_net
{

	UdpClient::UdpClient(spIoService ioService): 
			UdpSession(ioService), m_resolver(*ioService),
			m_serverConnection()
	{

	}
	
	void UdpClient::ConnectToServer(udp::endpoint ep)
	{
		m_serverConnection.m_endpoint = ep;
		//On handshake failure.
		if ( !HandshakeWithServer() )
		{
			

		}
	}

	bool UdpClient::HandshakeWithServer()
	{
		if (!m_socket.available())
			return false;

		//Setup initial handshake request.
		m_serverConnection.m_outBuffer[0] = MPN_UDP_PKT_SPECIAL_BYTE;
		m_serverConnection.m_outBuffer[1] = MPN_UDP_PKT_HANDSHAKE;
		m_serverConnection.m_outBuffer[2] = MPN_UDP_PKT_SPECIAL_BYTE;
		m_serverConnection.m_outBuffer[3] = MPN_UDP_PKT_END_DATA;

		//Send the handshake request.
		WriteDataToSocket(
					m_serverConnection.m_outBuffer, 
					m_serverConnection.m_endpoint, 
					MPN_UDP_PKT_BUFFER_MAX);

		//Wait for a response
		udp::endpoint endpoint;
		m_serverConnection.m_inBufferIndex = 
			ReadDataFromSocket(
				m_serverConnection.m_inBuffer, endpoint);

		//Check if responder matches the target
		if ( endpoint != m_serverConnection.m_endpoint )
			return false;

		//Decode response


		return true;
	}

	void UdpClient::ThreadInitialization()
	{
	}

	void UdpClient::ThreadUpdate()
	{
		while(!TryLock()){Sleep(1);}
		
		//1- Read Operation

		//IF data socket is open
		if (m_socket.is_open())
		{
			//Read available data to parse
			if (m_socket.available())
			{
				if ( !m_serverConnection.m_inBufferReady)
				{
					//Read buffer input
					udp::endpoint sender;
					m_serverConnection.m_inBufferIndex =
						ReadDataFromSocket(
							m_serverConnection.m_inBuffer, 
							sender,
							MPN_UDP_PKT_BUFFER_MAX);
					//--
					m_serverConnection.m_inBufferReady = true;
				}
			}

			//Write available data
			if (m_serverConnection.m_outBufferReady)
			{
				WriteDataToSocket(
					m_serverConnection.m_outBuffer, 
					m_serverConnection.m_endpoint, 
					MPN_UDP_PKT_BUFFER_MAX);
				//--
					m_serverConnection.m_outBufferReady = false;
			}
		}

		//2- Parse and Build Operations
		if ( m_serverConnection.m_inBufferReady ) 
			ParseInputBuffer();
		if ( !m_serverConnection.m_outBufferReady ) 
			BuildOutputBuffer();

		Unlock();
	}
	
	void UdpClient::ParseInputBuffer()
	{
		
		//m_inBufferReady = false;
	}

	void UdpClient::BuildOutputBuffer()
	{
		
		//m_outBufferReady = true;
	}

	void UdpClient::ThreadShutdown()
	{
		
	}


}